package com.gani.scoreboardmain;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class ScoreBoardMain extends ActionBarActivity {

    private TableLayout tableLayout = null;
    private Button btnAddUser = null;
    private Button btnStartGame = null;
    private Button btnEndGame = null;
    private EditText txtPlayerName = null;
    private Map<String, Integer> playerList = new LinkedHashMap<String, Integer>();
    private Map<String, Integer> playerListCopy = new LinkedHashMap<String, Integer>();
    final Context context = this;

    // Layout params declaration
    final TableLayout.LayoutParams tlp = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, 15);
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.fragment_score_board_main);
        tableLayout = (TableLayout)findViewById(R.id.tbl_board_content);
        btnAddUser = (Button)findViewById(R.id.btn_add_player);
        txtPlayerName = (EditText)findViewById(R.id.txt_name);
        txtPlayerName.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
        btnStartGame = (Button) findViewById(R.id.btn_start_game);
        btnEndGame = (Button) findViewById(R.id.btn_end_game);

        btnAddUser.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(txtPlayerName.getText().toString().isEmpty())
                {
                    Toast msg = Toast.makeText(getBaseContext(),
                            "Please provide a player name..", Toast.LENGTH_LONG);
                    msg.show();
                }
                else
                {
                    playerList.put(txtPlayerName.getText().toString(), 0);
                    addRows(tableLayout, playerList, txtPlayerName.getText().toString());
                    txtPlayerName.setText("");
                }
            }
        });

        btnStartGame.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // Enable-disable necessary controls
                txtPlayerName.setEnabled(false);
                btnAddUser.setEnabled(false);
                btnStartGame.setEnabled(false);
                btnEndGame.setEnabled(true);
                // Copy List of players
                playerListCopy = playerList;
                // Create Score Board
                drawScoreBoard();
            }
        });

        btnEndGame.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // Enable-disable controls
                btnStartGame.setEnabled(true);
                txtPlayerName.setEnabled(true);
                btnAddUser.setEnabled(true);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                // set title
                alertDialogBuilder.setTitle("Score List");
                TableLayout finalScores = new TableLayout(context);
                finalScores.setPadding(10, 5, 10, 5);
                playerList = sortByValue(playerList);
                Iterator it = playerList.entrySet().iterator();
                int i = 1;
                int winningScore = 0;
                while(it.hasNext())
                {
                    TableRow tr = new TableRow(context);

                    Map.Entry pairs = (Map.Entry) it.next();
                    TextView tvOrder = new TextView(context);
                    tvOrder.setText(String.valueOf(i));
                    tvOrder.setWidth(40);
                    tvOrder.setPadding(5, 0, 0, 0);

                    TextView tvName = new TextView(context);
                    tvName.setText(pairs.getKey().toString());
                    tvName.setWidth(260);
                    tvName.setPadding(5, 0, 0, 0);

                    TextView tvScore = new TextView(context);
                    tvScore.setText(pairs.getValue().toString());
                    tvScore.setWidth(40);
                    tvScore.setPadding(5, 0, 0, 0);

                    tr.addView(tvOrder);
                    tr.addView(tvName);
                    tr.addView(tvScore);
                    tr.setLayoutParams(tlp);
                    tr.setPadding(5, 5, 5, 5);

                    if (i == 1)
                    {
                        tr.setBackgroundColor(Color.GRAY);
                        winningScore = Integer.parseInt(pairs.getValue().toString());
                    }
                    else if (winningScore == Integer.parseInt(pairs.getValue().toString()))
                    {
                        tr.setBackgroundColor(Color.GRAY);
                    }

                    finalScores.addView(tr);

                    i++;
                }
                alertDialogBuilder.setView(finalScores);
                // set dialog message
                alertDialogBuilder
                        .setCancelable(true)
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                        drawScoreBoard();
                    }
                });
                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();
                // show it
                alertDialog.show();
                // Clear scores
                playerList = playerListCopy;
                drawScoreBoard();
            }
        });
    }

    public void addRows(TableLayout Tlayout, Map<String, Integer> list, String key) {
        TableRow Trow = new TableRow(getApplicationContext());

        final TextView playerName = new TextView(getApplicationContext());
        playerName.setText(key);
        playerName.setTextSize(18);
        Trow.addView(playerName);
        Trow.setLayoutParams(tlp);
        Trow.setMinimumHeight(25);
        Trow.setPadding(5, 5, 5, 5);

        Tlayout.addView(Trow);
        Trow.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // row is your row, the parent of the clicked button
                final View row = (View) playerName.getParent();
                // container contains all the rows, you could keep a variable somewhere else to the container which you can refer to here
                final ViewGroup container = ((ViewGroup)row.getParent());
                // get the selected player name
                final String selectedPlayer = ((TextView)playerName).getText().toString();

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                // set title
                alertDialogBuilder.setTitle("Delete User");

                // set dialog message
                alertDialogBuilder
                        .setMessage("Do you want to delete player: " + selectedPlayer)
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, close
                                // current activity
                                playerList.remove(selectedPlayer);
                                container.removeView(row);
                                container.invalidate();
                                Toast msg = Toast.makeText(getBaseContext(),
                                        "Deleted player: " + selectedPlayer , Toast.LENGTH_LONG);
                                msg.show();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            }
                        });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            }
        });

        Toast msg = Toast.makeText(getBaseContext(),
                "Player added..", Toast.LENGTH_LONG);
        msg.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.score_board_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_score_board_main, container, false);
            return rootView;
        }
    }

    static Map sortByValue(Map map) {
        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) ((Map.Entry) (o2)).getValue())
                        .compareTo(((Map.Entry) (o1)).getValue());
            }
        });

        Map result = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry)it.next();
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    public void drawScoreBoard()
    {
        tableLayout.setPadding(5, 5, 5, 5);
        tableLayout.removeAllViewsInLayout();
        Iterator it = playerList.entrySet().iterator();
        int i = 0;

        while (it.hasNext())
        {
            Map.Entry pairs = (Map.Entry) it.next();
            final TextView playerName = new TextView(getApplicationContext());
            playerName.setText(pairs.getKey().toString());
            playerName.setPadding(9, 0, 0, 0);
            playerName.setWidth(200);
            playerName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

            final TextView playerScore = new TextView(getApplicationContext());
            playerScore.setText(pairs.getValue().toString());
            playerScore.setMinWidth(60);
            playerScore.setWidth(10);
            playerScore.setPadding(9, 0, 0, 0);
            playerScore.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

            TableRow Trow = new TableRow(getApplicationContext());
            Trow.setLayoutParams(tlp);
            Trow.addView(playerName);
            Trow.addView(playerScore);
            Trow.setPadding(5, 5, 5, 5);
            // playerScore.setHeight(Math.round(screenHeight/12));

            i++;
            if(i%2 == 0)
                Trow.setBackgroundColor(Color.GRAY);
            else
                Trow.setBackgroundColor(Color.DKGRAY);

            tableLayout.addView(Trow);

            Trow.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    // row is your row, the parent of the clicked button
                    final View row = (View) playerName.getParent();
                    // container contains all the rows, you could keep a variable somewhere else to the container which you can refer to here
                    final ViewGroup container = ((ViewGroup)row.getParent());
                    // get the selected player name
                    final String selectedPlayer = ((TextView)playerName).getText().toString();

                    final EditText txtEditScore = new EditText(context);
                    txtEditScore.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);

                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                    // set title
                    alertDialogBuilder.setTitle("Update score");
                    alertDialogBuilder.setView(txtEditScore);

                    // set dialog message
                    alertDialogBuilder
                            .setMessage("So, what did " + selectedPlayer + " score this time?")
                            .setCancelable(false)
                            .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    if (txtEditScore.getText().toString().isEmpty())
                                        txtEditScore.setText(0);
                                    int currentScore = playerList.get(selectedPlayer);
                                    int scoreUpdate = Integer.parseInt(txtEditScore.getText().toString());
                                    int newScore = currentScore + scoreUpdate;
                                    playerList.put(selectedPlayer, newScore);
                                    playerScore.setText(String.valueOf(newScore));
                                    playerScore.refreshDrawableState();
                                }
                            })
                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // if this button is clicked, just close
                                    // the dialog box and do nothing
                                    dialog.cancel();
                                }
                            });
                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    // show it
                    alertDialog.show();
                    txtEditScore.requestFocus();
                }
            });
        }
    }
}